﻿using System.Collections.Generic;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;

namespace Yamfinder.Data
{
    public class LexicalRepository : ILexicalRepository
    {
        private readonly MongoCollection _collection;
        public const string CollectionName = "Data";
        
        public LexicalRepository(IDataSource dataSource)
        {
            _collection = dataSource.GetRawCollection(CollectionName);
        }

        public IList<LexicalEntry> Query(IMongoQuery mongoQuery)
        {
            var results = _collection.FindAs<LexicalEntry>(mongoQuery);
            var resultsList = new List<LexicalEntry>(results);
            return resultsList;
        }

        public LexicalEntry Get(ObjectId id)
        {
            return _collection.FindOneAs<LexicalEntry>(MatchId(id));
        }

        public void Insert(LexicalEntry lexicalEntry)
        {
            _collection.Insert(lexicalEntry);
        }

        public void Save(LexicalEntry lexicalEntry)
        {
            _collection.Save(lexicalEntry);
        }

        public void Remove(ObjectId id)
        {
            _collection.Remove(MatchId(id));
        }

        private QueryComplete MatchId(ObjectId id)
        {
            return MongoDB.Driver.Builders.Query.EQ("_id", id);
        }
    }
}